var Enum = require('Enum')
var ParticleSystem = require('ParticleSystem')

cc.Class({
    extends: require('FrameComponent'),

    properties: {
        camp : Enum.CAMP.neutral,
        skillType : {
            type : Number,
            default : 0
        }
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        this._launchers = [];
        this.b_isVitual = false;
        this._particleSys = [];
    },

    reset(){
        this.unscheduleAllCallbacks();
        var children = this.node.children
        for(var i=0; i<children.length; i++){
            var ps = children[i].getComponent('ParticleSprite');
            if(ps){
                // ps.recovery();
            } else {
                children[i].destroy();
            }
        }
        this._particleSys = []
    },

    addLauncher(skills){
        if (!this.skillParentNode) {
            this.skillParentNode = global.GameLoop.GameMgr.bulletLayer
        }
        var someParticleSystems = {};
        for(var i=0; i<skills.length; i++){
            let skillbase = global.Common.deepCopy(skills[i]);
            skillbase.camp = this.camp;
            var action = skillbase.action || ''
            let skillName = skillbase.name+action
            var sps = someParticleSystems[skillName]
            if(!sps){
                sps = [];
                someParticleSystems[skillName] = sps;
            }
            sps.push({
                name : skillName,
                skillbase:skillbase,
                dx : skillbase.dx || 0,
                dy : skillbase.dy || 0,
                dr : skillbase.r || 0
            })
        }
        for(var skillkey in someParticleSystems){
            let team = someParticleSystems[skillkey];
            let skillbase = team[0].skillbase;
            let skillName = skillbase.name

            let particle = global.Common.deepCopy(global.DataCfg.weapon[skillName])
            if (!particle) {
                cc.warn('没有找到粒子文件')
                continue;
            }
            particle.poolName = skillbase.poolName || skillName
            // var nodename = skillName.substring(Math.max(skillName.indexOf('/') + 1, 0));
            let ps = new cc.Node().addComponent(ParticleSystem);
            // var nodename = skillName.replace('/','-')
            ps.node.name = skillbase.skillcfg;
            ps.setAutoUpdate(false);
            ps.isLocal = this.isLocal
            this.node.addChild(ps.node) //添加一个粒子发射器
            this._particleSys.push(ps);

            ps.node.rotation = skillbase.r ? skillbase.r : 0;

            if(skillbase['repeat']) particle.repeat = skillbase['repeat']
            if(skillbase['emissionRate']) particle.emissionRate = skillbase['emissionRate']
            if(skillbase['speed']) particle.speed = skillbase['speed']
            if(skillbase['spriteFrame']) particle.spriteFrame = skillbase['spriteFrame']
            if(skillbase['roffset']) ps.node.rotation+= skillbase['roffset'] * global.Common.randomInteger()


            ps.node._skillBase = skillbase

            ps.setParticleLayer(this.skillParentNode)
            ps.setLauncherData(team)
            ps.loadData(particle);

            ps.addEvent(ParticleSystem.Event.CREATE, this.onParticleCreate.bind(this))
            ps.addEvent(ParticleSystem.Event.DESTROY, function(no){
                if(this.node){
                    this.onParticleDestroy(no);
                }
                // } else {
                //     cc.log('')
                // }
                var bc = no.detail.node.getComponent('Bullet')
                bc.activeColldier = false;
                bc._destroyImmediate();
                
                
                
            }.bind(this))

            skillbase.delay = skillbase.delay ? skillbase.delay : 0
            skillbase.offset = skillbase.offset ? skillbase.offset : 0
            var time = skillbase.delay + skillbase.offset * Math.random() * (Math.random() < 0.5 ? -1 : 1)
            if (time != 0) {
                ps.enabled = false;
                this.scheduleOnce(function () {
                    ps.enabled = true
                    skillbase.action && self.runSkillAction(skillbase.action, ps.node)
                }, time)
            } else {
                skillbase.action && this.runSkillAction(skillbase.action, ps.node)
            }
        }
    },
    onParticleCreate(no){
        if(!no.detail){
            return;
        }
        no.detail.setAutoUpdate(false);
        var skillBase = no.detail.node._source
        var bullet = no.detail.node.addComponent('Bullet')
        bullet.setCamp(skillBase.camp)
        bullet.setOptions(skillBase);
        bullet.activeColldier = true
        this._launchers.push(no);
        if(skillBase.aim){
            var players = global.GameLoop.GameMgr.getPlayers()
            var idx = Math.floor(Math.random() * Object.keys(players).length)
            var speed = no.detail.node._particle.speedInit;
            var p1 = no.detail.node.getPosition();
            var p2 = players[idx].node.getPosition();

            var len = p2.sub(p1).mag()
            var a = Math.acos((p2.x - p1.x) / len)
            var r = a;
            if (p2.y < p1.y) {
                r = 2 * Math.PI - r;
            }
            // // r = Math.PI /3;
            // cc.log('角度',r*180/Math.PI);
            var dx = Math.cos(r) * speed
            var dy = Math.sin(r) * speed
            no.detail.node._particle.speed = cc.v2(dx, dy)
            no.detail.node.rotation = 270 - r * 180 / Math.PI
        }
    },
    onParticleDestroy(no){
        for(var i=0; i<this._launchers.length; i++){
            var lc = this._launchers[i];
            if(lc.target == no.target){
                this._launchers.splice(i,1);
                return;
            }
        }
        // cc.log('onParticleDestroy:',no)
    },
    gameUpdate(dt){
        // for(var i=0; i<this._particleSys.length; i++){
        //     var ps = this._particleSys[i];
        //     ps.gameUpdate(dt);
        // }
    }
});
